package club.gskj.system.service.impl;

import club.gskj.handler.BusinessException;
import club.gskj.response.ResultCode;
import club.gskj.system.entity.User;
import club.gskj.system.mapper.UserMapper;
import club.gskj.system.myenum.UserStatusEnum;
import club.gskj.system.myenum.UserTypeEnum;
import club.gskj.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.xmlbeans.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 康纳~
 * @since 2020-11-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public IPage<User> findUserPage(Page<User> page, QueryWrapper<User> wrapper) {
        return this.baseMapper.findUserPage(page, wrapper);
    }

    @Override
    public int addUser(User user) {

        // 判断是否 添加了重复的 用户名
        String username = user.getUsername();

        QueryWrapper<User> wra = new QueryWrapper<>();

        // 判断 用户名是否存在
        wra.eq("username", username);
        Integer integer = this.baseMapper.selectCount(wra);
        if (integer > 0) {
            throw new BusinessException(ResultCode.USER_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ALREADY_EXIST.getMessgae());
        }

        // 设置 盐值
        String salt = UUID.randomUUID().toString().substring(0, 32).replaceAll("-", "");
        user.setSalt(salt);

        // 使用security 自带的密码策略
        String encodePwd = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePwd);

        // 设置用户类型
        user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());

        // 用户状态
        user.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());

        //是否以删除， 默认不删除
        user.setDeleted(false);

        //TODO 默认设置 创建时间、更新时间

        return this.baseMapper.insert(user);
    }
}
